package com.example.heimashop.view.activity;

import android.content.DialogInterface;
import android.content.Intent;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.heimashop.R;
import com.example.heimashop.base.BaseActivity;
import com.example.heimashop.database.OrderDao;
import com.example.heimashop.databinding.ActivityOrderListBinding;
import com.example.heimashop.model.Order;
import com.example.heimashop.utils.ToastUtils;
import com.example.heimashop.view.adapter.OrderAdapter;
import com.google.android.material.tabs.TabLayout;

import java.util.List;

/**
 * 订单列表页面
 * 页面12: OrderListActivity - 订单列表页面
 */
public class OrderListActivity extends BaseActivity<ActivityOrderListBinding> {

    private OrderAdapter adapter;
    private OrderDao orderDao;
    private String currentStatus = "all"; // 当前选中的状态

    @Override
    protected ActivityOrderListBinding getViewBinding() {
        return ActivityOrderListBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        // 初始化数据库
        orderDao = new OrderDao(this);

        // 添加Tab
        binding.tabLayout.addTab(binding.tabLayout.newTab().setText(R.string.order_status_all));
        binding.tabLayout.addTab(binding.tabLayout.newTab().setText(R.string.order_status_wait_pay));
        binding.tabLayout.addTab(binding.tabLayout.newTab().setText(R.string.order_status_wait_send));
        binding.tabLayout.addTab(binding.tabLayout.newTab().setText(R.string.order_status_wait_receive));
        binding.tabLayout.addTab(binding.tabLayout.newTab().setText(R.string.order_status_completed));

        // 设置RecyclerView
        binding.rvOrders.setLayoutManager(new LinearLayoutManager(this));
        adapter = new OrderAdapter();
        binding.rvOrders.setAdapter(adapter);

        // 设置适配器监听
        setupAdapter();

        // 根据传入的状态选中对应Tab
        String status = getIntent().getStringExtra("status");
        if (status != null) {
            currentStatus = status;
            switch (status) {
                case "wait_pay":
                    binding.tabLayout.selectTab(binding.tabLayout.getTabAt(1));
                    break;
                case "wait_send":
                    binding.tabLayout.selectTab(binding.tabLayout.getTabAt(2));
                    break;
                case "wait_receive":
                    binding.tabLayout.selectTab(binding.tabLayout.getTabAt(3));
                    break;
            }
        }
    }

    @Override
    protected void initData() {
        loadOrders();
    }

    @Override
    protected void initListener() {
        binding.ivBack.setOnClickListener(v -> finish());

        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // 根据选中的Tab加载不同状态的订单
                int position = tab.getPosition();
                switch (position) {
                    case 0:
                        currentStatus = "all";
                        break;
                    case 1:
                        currentStatus = "wait_pay";
                        break;
                    case 2:
                        currentStatus = "wait_send";
                        break;
                    case 3:
                        currentStatus = "wait_receive";
                        break;
                    case 4:
                        currentStatus = "completed";
                        break;
                }
                loadOrders();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    /**
     * 设置适配器监听
     */
    private void setupAdapter() {
        adapter.setListener(new OrderAdapter.OnOrderItemListener() {
            @Override
            public void onPay(Order order) {
                // 显示支付确认对话框
                new AlertDialog.Builder(OrderListActivity.this)
                        .setTitle("确认支付")
                        .setMessage("订单金额：¥" + String.format("%.2f", order.getTotalPrice()) + "\n确认支付吗？")
                        .setPositiveButton("确认支付", (dialog, which) -> {
                            // 模拟支付
                            orderDao.updateOrderStatus(order.getId(), "wait_send");
                            ToastUtils.showShort(OrderListActivity.this, "支付成功");
                            loadOrders();
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }

            @Override
            public void onCancel(Order order) {
                // 显示取消订单确认对话框
                new AlertDialog.Builder(OrderListActivity.this)
                        .setTitle("取消订单")
                        .setMessage("确定要取消订单吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            // 取消订单
                            orderDao.updateOrderStatus(order.getId(), "cancelled");
                            ToastUtils.showShort(OrderListActivity.this, "订单已取消");
                            loadOrders();
                        })
                        .setNegativeButton("我再想想", null)
                        .show();
            }

            @Override
            public void onConfirm(Order order) {
                // 显示确认收货对话框
                new AlertDialog.Builder(OrderListActivity.this)
                        .setTitle("确认收货")
                        .setMessage("请确认您已收到商品，确认收货后订单将完成。")
                        .setPositiveButton("确认收货", (dialog, which) -> {
                            // 确认收货
                            orderDao.updateOrderStatus(order.getId(), "completed");
                            ToastUtils.showShort(OrderListActivity.this, "确认收货成功");
                            loadOrders();
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }

            @Override
            public void onDelete(Order order) {
                // 显示删除订单确认对话框
                new AlertDialog.Builder(OrderListActivity.this)
                        .setTitle("删除订单")
                        .setMessage("确定要删除该订单吗？删除后无法恢复。")
                        .setPositiveButton("删除", (dialog, which) -> {
                            // 删除订单
                            int result = orderDao.deleteOrder(order.getId());
                            if (result > 0) {
                                ToastUtils.showShort(OrderListActivity.this, "订单已删除");
                                loadOrders();
                            } else {
                                ToastUtils.showShort(OrderListActivity.this, "删除失败");
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });
    }

    /**
     * 加载订单列表
     */
    private void loadOrders() {
        List<Order> orders;
        if ("all".equals(currentStatus)) {
            orders = orderDao.getAllOrders();
        } else {
            orders = orderDao.getOrdersByStatus(currentStatus);
        }
        adapter.setData(orders);
    }
}
